//
//  CPDropDownView.m
//  CPDropdownView
//
//  Created by 美鑫科技 on 16/5/9.
//  Copyright © 2016年 MorpLCP. All rights reserved.
//

#import "CPDropDownView.h"

#define SUPERWIDTH self.superview.frame.size.width
#define SUPERHEIGHT self.superview.frame.size.height

@interface CPDropDownView ()

@property (nonatomic, assign) BOOL isOpen;

@end

@implementation CPDropDownView

- (instancetype)initWithFrame:(CGRect)frame ReferenceView:(UIView *)view{
    self = [super initWithFrame:frame];
    if (self) {
        UIBlurEffect *blur = [UIBlurEffect effectWithStyle:(UIBlurEffectStyleDark)];
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blur];
        [self addSubview:effectView];
        self.isOpen = NO;
    }
    return self;
}

- (void)showDropView{
    [self showDropViewWithDropDirection:self.direction];
}

- (void)showDropViewWithDropDirection:(CPDropDirection)direction{
    if (!self.isOpen) {
        CAKeyframeAnimation * keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        keyFrame.values = [NSArray arrayWithObjects:
                           [NSValue valueWithCGPoint:CGPointMake(self.superview.frame.size.width / 2.0, -self.superview.frame.size.height / 2.0)],
                           [NSValue valueWithCGPoint:CGPointMake(self.superview.frame.size.width / 2.0, self.superview.frame.size.height / 2.0)],
                           [NSValue valueWithCGPoint:CGPointMake(self.superview.frame.size.width / 2.0, self.superview.frame.size.height / 2.0 - 50 * self.magnitude)],
                           [NSValue valueWithCGPoint:CGPointMake(self.superview.frame.size.width / 2.0, self.superview.frame.size.height / 2.0)],nil];
        keyFrame.duration = self.duration;
        keyFrame.removedOnCompletion = NO;
        keyFrame.fillMode = kCAFillModeForwards;
        keyFrame.delegate = self;
        [self.layer addAnimation:keyFrame forKey:@"dropDown"];
    }
}

//- (void)addPanGestureRecognizer

- (void)dismissDropView{
    [self.layer removeAnimationForKey:@"dropDown"];
    [UIView transitionWithView:self duration:self.duration options:(UIViewAnimationOptionTransitionNone) animations:^{
        self.frame = CGRectMake(0, -self.superview.frame.size.height, self.superview.frame.size.width, self.superview.frame.size.height);
    } completion:^(BOOL finished) {
        self.isOpen = NO;
    }];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if ([anim isKindOfClass:[CAKeyframeAnimation class]]) {
        self.frame = CGRectMake(0, 0, self.superview.frame.size.width, self.superview.frame.size.height);
        self.isOpen = YES;
    }
}

@end
